package edu.ynu.se.xiecheng.achitectureclass.common.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestParam String username, @RequestParam String password) {
        String token = userService.login(username, password);
        if (token != null) {
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(401).body(null);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Long>> register(@RequestParam String username, @RequestParam String password) {
        User user = userService.register(username, password);
        if (user != null) {
            Map<String, Long> response = new HashMap<>();
            response.put("userId", user.getId());
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(400).body(null);
        }
    }
}
